package com.zhongshengnetwork.rightbe.lang.activity;

import static android.os.ext.SdkExtensions.getExtensionVersion;

import android.Manifest;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
//import android.support.annotation.NonNull;
//import android.support.v4.app.ActivityCompat;
//import android.support.v4.content.FileProvider;
//import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
//import android.support.v7.widget.RecyclerView;
//import android.support.v7.widget.StaggeredGridLayoutManager;
//import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.InputFilter;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.hys.utils.AppUtils;
import com.hys.utils.DensityUtils;
import com.hys.utils.ImageUtils;
import com.hys.utils.InitCacheFileUtils;
import com.hys.utils.SdcardUtils;
import com.hys.utils.ToastUtils;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.MainActivity;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.DateUtil;
import com.zhongshengnetwork.rightbe.common.JsonMap;
import com.zhongshengnetwork.rightbe.common.StatusbarUtils;
import com.zhongshengnetwork.rightbe.common.callback.PermissionCallback;
import com.zhongshengnetwork.rightbe.dbmodel.LangPublishdbModel;
import com.zhongshengnetwork.rightbe.dbservice.LangPublishService;
import com.zhongshengnetwork.rightbe.gsonmodel.DateModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangTypeModel;
import com.zhongshengnetwork.rightbe.imageviewer.ImageLoader;
import com.zhongshengnetwork.rightbe.imageviewer.ViewData;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.BuildConfig;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ImageCompressUtils;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.UriToPathUtil;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.game.activity.HeaderWordActivity;
import com.zhongshengnetwork.rightbe.game.activity.SubjectWordActivity;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.view.MyCallBack;
import com.zhongshengnetwork.rightbe.lang.view.OnRecyclerItemClickListener;
import com.zhongshengnetwork.rightbe.lang.view.PostArticleImgAdapter;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.NewClassifyActivity;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTListActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class LangPublishActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener{

    //图片裁剪比例
    public static final int Original_Type = 0; //原图
    public static final int Crop_Type_30_17 = 1;
    public static final int Crop_Type_1_1 = 2;
    public static final int Crop_Type_16_9 = 3;
    public static final int Crop_Type_3_2 = 4;
    public static final int Crop_Type_4_3 = 5;
    public static final int Crop_Type_2_1 = 6;
    public static final int Crop_Type_2_3 = 7;
    public static final int Crop_Type_3_4 = 8;

    public static final String[] CropMenus = new String[]{"原图","30:17","1:1","16:9","3:2","4:3","2:1","2:3","3:4"};

    public static final String FILE_DIR_NAME = "com.zhongshengnetwork.rightbe";//应用缓存地址
    public static final String FILE_IMG_NAME = "images";//放置图片缓存
    //public static final int IMAGE_SIZE = 9;//可添加图片最大数
    public int maxImgCount = 9;
    private static final int REQUEST_PUBLISH = 10002;
    private static final int LANG_TYPE = 1119;
    private static final int REQUEST_LOCATION = 1211;//地理位置
    private static final int TAKE_PICTURE = 1212;//拍照
    private static final int SELECT_WZT = 1213;
    private static final int CHOOSE_PICTURE = 1214;//从相册选择
    private static final int FILTER_PICTURE = 1215; //图片滤镜
    private static final int REQUEST_PERMISSION = 10003;
    private static final int PHOTO_PICKER_REQUEST_CODE = 10004; //android 13从相册选择一张图片
    private static final int PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE = 10005; //android 13从相册选择多张图片

    private static final int MaxLength = 600;

    private static String imageFileName = "";//拍照图片名称
    private static String cropFilePath = "";
    private static Uri cropUrl = null;
    public boolean isDealWithImg = false;//是否正在处理图片

    private TopBarView topbar;

    private ArrayList<String> originImages;//原始图片
    private ArrayList<String> dragImages;//压缩长宽后图片
    private Context mContext;
    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;
    private RecyclerView rcvImg;
    private TextView tv;//删除区域提示
    private EditText et_content;

    private String imgString = "";
    private int imgIndex = 0;
    private QiniuModel qiniuModel = null;
    private boolean isUploading = false;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private Handler mHandler = null;
    private static int delay = 100;
    private static int period = 500;  //1s
    private boolean timerFlag = false;
    public AVLoadingIndicatorView avi;
    private boolean isRepublish = false;
    private String mLangid;

    private RelativeLayout publish_menu_original;
    private LinearLayout publish_menu_original_line;
    private TextView publish_menu_original_title;
    private ImageView publish_menu_original_select;

    private RelativeLayout publish_menu_type;
    private LinearLayout publish_menu_type_line;
    private TextView publish_menu_type_title;
    private TextView publish_menu_type_text;
    private RelativeLayout publish_menu_visible;
    private TextView publish_menu_visible_text;

    private RelativeLayout publish_menu_wzt;
    private LinearLayout publish_menu_wzt_line;
    private TextView publish_menu_wzt_title;
    private TextView publish_menu_wzt_text;

    private RelativeLayout publish_menu_timing;
    private TextView publish_menu_timing_text;
    private LinearLayout publish_line4;

    //图片浏览
    public ImageViewer imagePreivew;
    private int imgW = 0;
    List<ViewData> mViewDatas = new ArrayList<ViewData>();
    List<Object> mImageList = new ArrayList<Object>();

    private List<String> nameList = null;
    private List<String> itemList = null;
    private String createtime; //定时发布时间
    private int status = 0;//0-公开 4-私密
    private int type = 0;//默认类型

    private boolean isPublishing = false;//发布状态，控制重复发布
    private String titlename = "";

    private String nation;
    private String province;
    private String city;
    private String area;
    private String location;
    private double longtitude;
    private double latitude;
    private String noname;
    private String original = "0";
    private String wztTitle = "";
    private String wztId = "";

    private boolean isWZT = false; //是否是微纸条

    List<LangTypeModel> commonTypeList = null;
    private RelativeLayout common_lang_type;
    private TextView one_text;
    private TextView two_text;
    private TextView three_text;
    private TextView four_text;
    private TextView five_text;

    private LinearLayout filter_layout;
    private TextView filter_title;


    //绑定手机号
    private boolean bindMobile(){
        if (CommonUtils.isLogin() == true){
            if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
                if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
                    Intent intent = new Intent(LangPublishActivity.this, BDThirdActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
        }
        return false;
    }

    public static void startPublishActivity(Context context, ArrayList<String> images, String content, String langid) {
        Intent intent = new Intent(context, LangPublishActivity.class);
        intent.putStringArrayListExtra("img", images);
        intent.putExtra("isRepublish",true);
        intent.putExtra("content",content);
        intent.putExtra("langid",langid);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_lang_publish);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getRightTextView().setText("发布");
        topbar.getRightTextView().setTextSize(15);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(LangPublishActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                publishLang();
            }
        });
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);

        if (CommonUtils.isLogin() == true){
            String d = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.CommonTypeName+CustomApplication.loginModel.getUid(), "");
            if (!CommonUtils.isEmpty(d)){
                commonTypeList = GsonTools.getLangTypeCommon(d);;
            }
        }

        original = "0";
        publish_menu_original = (RelativeLayout) findViewById(R.id.publish_menu_original);
        publish_menu_original_line = (LinearLayout) findViewById(R.id.publish_menu_original_line);
        publish_menu_original_title = (TextView) findViewById(R.id.publish_menu_original_title);
        publish_menu_original_select = (ImageView) findViewById(R.id.publish_menu_original_select);

        publish_menu_type = (RelativeLayout) findViewById(R.id.publish_menu_type);
        publish_menu_type_line = (LinearLayout) findViewById(R.id.publish_menu_type_line);
        publish_menu_type.setClickable(true);
        publish_menu_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                if (type == 30 || type == 116){
                    //生活分享，获取所在位置
                    PermissionUtils.isLocationNote(LangPublishActivity.this, new PermissionCallback() {
                        @Override
                        public void onResult(boolean flag, boolean showAlert) {
                            if (flag == true){
                                Intent intent = new Intent(LangPublishActivity.this,SearchLocationActivity.class);
                                startActivityForResult(intent, REQUEST_LOCATION);
                            }
                        }
                    });
                    return;
                }else if (type == 44 || type == 21){
                    onClickNicknameVisible();
                    return;
                }
                Intent intent = new Intent(LangPublishActivity.this,PublicTypeActivity.class);
                startActivityForResult(intent, LANG_TYPE);
            }
        });
        publish_menu_type_title = (TextView) findViewById(R.id.publish_menu_type_title);
        publish_menu_type_text = (TextView) findViewById(R.id.publish_menu_type_text);

        publish_menu_wzt = (RelativeLayout) findViewById(R.id.publish_menu_wzt);
        publish_menu_wzt.setClickable(true);
        publish_menu_wzt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                Intent intent = new Intent(LangPublishActivity.this, WZTListActivity.class);
                intent.putExtra("title","我的微纸条");
                intent.putExtra("dataType",1001);
                intent.putExtra("opType", 2);
                startActivityForResult(intent, SELECT_WZT);

            }
        });
        publish_menu_wzt_title = (TextView) findViewById(R.id.publish_menu_wzt_title);
        publish_menu_wzt_text = (TextView) findViewById(R.id.publish_menu_wzt_text);


        publish_menu_visible = (RelativeLayout) findViewById(R.id.publish_menu_visible);
        publish_menu_visible.setClickable(true);
        publish_menu_visible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                onClickVisible();
            }
        });
        publish_menu_visible_text = (TextView) findViewById(R.id.publish_menu_visible_text);

        publish_menu_timing = (RelativeLayout) findViewById(R.id.publish_menu_timing);
        publish_menu_timing.setClickable(true);
        publish_menu_timing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickTiming();
            }
        });
        publish_menu_timing_text = (TextView) findViewById(R.id.publish_menu_timing_text);
        publish_line4 = (LinearLayout) findViewById(R.id.publish_line4);
        boolean isCanTiming = false;
        if (CommonUtils.isLogin() == true){
            if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.whiteKey, false) == true){
                isCanTiming = true;
            }
        }
        if (isCanTiming == false){
            publish_menu_timing.setVisibility(View.GONE);
            publish_line4.setVisibility(View.GONE);
        }

        imagePreivew = (ImageViewer) findViewById(R.id.imagePreivew);

        status = getIntent().getIntExtra("status", 0);
        initView();
        initData();
        initRcv();

        common_lang_type = (RelativeLayout) findViewById(R.id.common_lang_type);
        boolean filterVisible = false;
        if (type == 30 || type == 21 || type == 44 || type == 116){
            common_lang_type.setVisibility(View.GONE);
            if (type == 21){
                filterVisible = true;
            }
        }else {
            filterVisible = true;
            if (commonTypeList == null || commonTypeList.size() == 0){
                common_lang_type.setVisibility(View.GONE);
            }else {
                common_lang_type.setVisibility(View.VISIBLE);
                one_text = (TextView) findViewById(R.id.one_text);
                two_text = (TextView) findViewById(R.id.two_text);
                three_text = (TextView) findViewById(R.id.three_text);
                four_text = (TextView) findViewById(R.id.four_text);
                five_text = (TextView) findViewById(R.id.five_text);
                for(int i = 0; i < commonTypeList.size(); i++){
                    if (i == 0){
                        one_text.setVisibility(View.VISIBLE);
                        one_text.setTextColor(AppThemeUtils.getInstance().getLangTypeTextColor());
                        one_text.setBackgroundResource(AppThemeUtils.getInstance().getLangTypeBgColor());
                        one_text.setText(commonTypeList.get(i).getName());
                        one_text.setTag(i);
                        one_text.setClickable(true);
                        one_text.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                type = commonTypeList.get((int)view.getTag()).getId();
                                String typeName = commonTypeList.get((int)view.getTag()).getName();
                                if (!CommonUtils.isEmpty(typeName)){
                                    publish_menu_type_text.setText(typeName);
                                }
                            }
                        });
                    }else if (i == 1){
                        two_text.setVisibility(View.VISIBLE);
                        two_text.setTextColor(AppThemeUtils.getInstance().getLangTypeTextColor());
                        two_text.setBackgroundResource(AppThemeUtils.getInstance().getLangTypeBgColor());
                        two_text.setText(commonTypeList.get(i).getName());
                        two_text.setTag(i);
                        two_text.setClickable(true);
                        two_text.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                type = commonTypeList.get((int)view.getTag()).getId();
                                String typeName = commonTypeList.get((int)view.getTag()).getName();
                                if (!CommonUtils.isEmpty(typeName)){
                                    publish_menu_type_text.setText(typeName);
                                }
                            }
                        });
                    }else if (i == 2){
                        three_text.setVisibility(View.VISIBLE);
                        three_text.setTextColor(AppThemeUtils.getInstance().getLangTypeTextColor());
                        three_text.setBackgroundResource(AppThemeUtils.getInstance().getLangTypeBgColor());
                        three_text.setText(commonTypeList.get(i).getName());
                        three_text.setTag(i);
                        three_text.setClickable(true);
                        three_text.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                type = commonTypeList.get((int)view.getTag()).getId();
                                String typeName = commonTypeList.get((int)view.getTag()).getName();
                                if (!CommonUtils.isEmpty(typeName)){
                                    publish_menu_type_text.setText(typeName);
                                }
                            }
                        });
                    }else if (i == 3){
                        four_text.setVisibility(View.VISIBLE);
                        four_text.setTextColor(AppThemeUtils.getInstance().getLangTypeTextColor());
                        four_text.setBackgroundResource(AppThemeUtils.getInstance().getLangTypeBgColor());
                        four_text.setText(commonTypeList.get(i).getName());
                        four_text.setTag(i);
                        four_text.setClickable(true);
                        four_text.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                type = commonTypeList.get((int)view.getTag()).getId();
                                String typeName = commonTypeList.get((int)view.getTag()).getName();
                                if (!CommonUtils.isEmpty(typeName)){
                                    publish_menu_type_text.setText(typeName);
                                }
                            }
                        });
                    }/*else if (i == 4){
                    five_text.setVisibility(View.VISIBLE);
                    five_text.setTextColor(AppThemeUtils.getInstance().getLangTypeTextColor());
                    five_text.setBackgroundResource(AppThemeUtils.getInstance().getLangTypeBgColor());
                    five_text.setText(commonTypeList.get(i).getName());
                    five_text.setTag(i);
                    five_text.setClickable(true);
                    five_text.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            type = commonTypeList.get((int)view.getTag()).getId();
                            String typeName = commonTypeList.get((int)view.getTag()).getName();
                            if (!CommonUtils.isEmpty(typeName)){
                                publish_menu_type_text.setText(typeName);
                            }
                        }
                    });
                }*/else {
                        break;
                    }
                }
            }

        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//5.0以下不支持裁剪
            filterVisible = false;
        }

        filter_layout = (LinearLayout) findViewById(R.id.filter_layout);
        filter_title = (TextView) findViewById(R.id.filter_title);
        filter_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        TextView filter_desc = (TextView) findViewById(R.id.filter_desc);
        filter_desc.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        if (filterVisible == true){
            filter_layout.setVisibility(View.VISIBLE);
            int filterType = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.FilterCoverKey, 0);
            filter_title.setText(CropMenus[filterType]);

            filter_layout.setClickable(true);
            filter_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showMenu();
                }
            });
        }else {
            filter_layout.setVisibility(View.INVISIBLE);
        }

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg == null){
                    return;
                }
                switch (msg.what) {
                    case 1:
                        if (isUploading == true){
                            break;
                        }
                        isUploading = true;
                        Bitmap bitmap = null;
                        for (; imgIndex < dragImages.size(); imgIndex++){
                            if (dragImages.get(imgIndex).contains("http")==false){
                                bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                                /*
                                if (bitmap != null){
                                    if (CommonUtils.deleteFileByPath(dragImages.get(imgIndex))==true){
                                        Log.e("TAG","文件删除成功:"+dragImages.get(imgIndex));
                                    }
                                }
                                */
                                System.out.print(imgIndex+"有图片\n");
                                imgIndex++;
                                break;
                            }else {
                                if (imgString.length() >0){
                                    imgString += ",";
                                }
                                imgString += dragImages.get(imgIndex);
                            }
                        }
                        if (bitmap == null){
                            System.out.print("开始发布\n");
                            stopTimer();
                            uploadLang();
                            isUploading = false;
                        }else {
                            System.out.print("开始上传图片\n");
                            uploadImg(bitmap,imgIndex-1);
                        }
                        break;
                    default:
                        break;
                }
            }
        };

        RelativeLayout lang_publish = (RelativeLayout) findViewById(R.id.lang_publish);
        lang_publish.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        publish_menu_original_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        publish_menu_type_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        LinearLayout publish_line1 = (LinearLayout) findViewById(R.id.publish_line1);
        publish_line1.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        LinearLayout publish_line2 = (LinearLayout) findViewById(R.id.publish_line2);
        publish_line2.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        LinearLayout publish_line3 = (LinearLayout) findViewById(R.id.publish_line3);
        publish_line3.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        publish_line4.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        publish_menu_original_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_type_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_type_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_wzt_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_wzt_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        TextView publish_menu_visible_title = (TextView) findViewById(R.id.publish_menu_visible_title);
        publish_menu_visible_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_visible_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_timing_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        TextView publish_tip = (TextView) findViewById(R.id.publish_tip);
        publish_tip.setTextColor(AppThemeUtils.getInstance().getLightTextColor());
        et_content.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        et_content.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());

    }

    private void showMenu(){

        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(LangPublishActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : CropMenus){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        which -= 1;
                        filter_title.setText(CropMenus[which]);
                        SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(AdvertUtils.FilterCoverKey, which);
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        back();
    }

    @Override
    public void onBackPressed()
    {
        Log.e("TAG","按下返回键了");
        back();
    }

    private void back(){
        hintKeyBoard();
        final CustomDialog.Builder builder = new CustomDialog.Builder(LangPublishActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否要放弃本次发布？");
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteTempFile();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void onClickVisible(){
        if (nameList == null){
            nameList = new ArrayList<String>();
            nameList.add("公开");
            nameList.add("私密");
            if (CommonUtils.isLogin() == true){
                if (SPManageUtils.getInstance(CustomApplication.mContext).getSPBoolean(AdvertUtils.whiteKey, false) == true){
                    nameList.add("新增内容");
                }
            }
        }
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(LangPublishActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : nameList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = nameList.get(which-1);
                        publish_menu_visible_text.setText(title);
                        if (which == 1){
                            status = 0;//公开
                        }else if(which == 2){
                            status = 4;//私密
                        }else {
                            status = 5; //新增内容
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    private void showDate(){

        long time = System.currentTimeMillis();
        time += 600000;
        long startTime = time;
        long endTime = time + 10*24*60*60*1000;

        DateModel now = CommonUtils.getDateModelForNumber(time/1000);
        DateModel start = CommonUtils.getDateModelForNumber(startTime/1000);
        DateModel end = CommonUtils.getDateModelForNumber(endTime/1000);

        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        selectedDate.set(Integer.valueOf(now.getYear()),Integer.valueOf(now.getMonth()),Integer.valueOf(now.getDay()), Integer.valueOf(now.getHour()), Integer.valueOf(now.getMinute()));
        startDate.set(Integer.valueOf(start.getYear()),Integer.valueOf(start.getMonth()),Integer.valueOf(start.getDay()));
        endDate.set(Integer.valueOf(end.getYear()),Integer.valueOf(end.getMonth()),Integer.valueOf(end.getDay()));

        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(LangPublishActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = DateUtil.getDateStr(date, "yyyy-MM-dd HH:mm");
                publish_menu_timing_text.setText(time);
                createtime = DateUtil.date2TimeStamp(time, "yyyy-MM-dd HH:mm");
                Log.e("TAG","时间戳："+createtime);
                status = 100;
            }
        }).setType(new boolean[]{true, true, true, true, true, false}).setDate(selectedDate).setRangDate(startDate,endDate).build();
        pvTime.setTitleText("选择时间");
        pvTime.show();
    }

    private void onClickTiming(){
        List<String> m = new ArrayList<String>();
        m.add("设置时间");
        m.add("关闭定时");
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(LangPublishActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : m){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        if (which == 1){//设置时间
                           showDate();
                        }else if(which == 2){//关闭定时
                            if (!CommonUtils.isEmpty(createtime)){
                                createtime = "";
                                if (status == 100){
                                    status = 0;
                                    publish_menu_visible_text.setText("公开");
                                }
                                publish_menu_timing_text.setText("选择时间");
                            }
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();

    }

    private void onClickNicknameVisible(){
        if (itemList == null){
            itemList = new ArrayList<String>();
            itemList.add("公开昵称");
            itemList.add("匿名发布");
        }
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(LangPublishActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : itemList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        String title = itemList.get(which-1);
                        publish_menu_type_text.setText(title);
                        if (which == 1){
                            noname = "0";
                        }else {
                            noname = "1";
                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    private void initData() {

        nation = "";
        province = "";
        city = "";
        area = "";
        location = "";
        longtitude = 0.0;
        latitude = 0.0;
        noname = "0";
        createtime = "";

        createtime = getIntent().getStringExtra("createtime");
        if (!CommonUtils.isEmpty(createtime)){
            status = 100;
            publish_menu_timing_text.setText(CommonUtils.getDate2String(Long.valueOf(createtime)*1000,"yyyy-MM-dd HH:mm"));
        }
        titlename = getIntent().getStringExtra("titlename");
        type = getIntent().getIntExtra("type", 0);
        if (!CommonUtils.isEmpty(titlename) && titlename.equals("微纸条")){
            isWZT = true;
        }else {
            isWZT = false;
        }

        isRepublish = getIntent().getBooleanExtra("isRepublish",false);
        if (isRepublish == true){
            et_content.setText(getIntent().getStringExtra("content"));
            mLangid = getIntent().getStringExtra("langid");
            if (getIntent().getIntExtra("status",0) == 4){
                status = 4;
                publish_menu_visible_text.setText("私密");
            }
            String typename = getIntent().getStringExtra("typename");
            if (!CommonUtils.isEmpty(typename)){
                titlename = typename;
                topbar.getTitleView().setText(titlename);
                et_content.setHint(CommonUtils.formatString(getIntent().getStringExtra("tipname")));
                type = getIntent().getIntExtra(APIKey.typeKey,0);
                noname = getIntent().getStringExtra("noname");
                if (CommonUtils.isEmpty(noname)){
                    noname = "0";
                }

                String n = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.NoNameKey,"0");
                if (n.equals("1")){
                    if (titlename.equals("心里话") || type == 44){
                        type = 44;
                        publish_menu_type_title.setText("昵称显示");
                        if (noname.equals("1")){
                            publish_menu_type_text.setText("匿名发布");
                        }else {
                            publish_menu_type_text.setText("公开昵称");
                        }

                    }else if (titlename.equals("生活分享") || type == 30){
                        type = 30;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                    }else if (titlename.equals("笔记") || titlename.equals("优秀笔记") || type == 116 || type == 117){
                        type = 116;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                    }else if (titlename.equals("话题探索") || type == 21){
                        type = 21;
                        publish_menu_type_title.setText("昵称显示");
                        if (noname.equals("1")){
                            publish_menu_type_text.setText("匿名发布");
                        }else {
                            publish_menu_type_text.setText("公开昵称");
                        }
//                    publish_menu_type.setVisibility(View.GONE);
//                    publish_menu_type_line.setVisibility(View.GONE);
                    }else {
                        publish_menu_type_text.setText(typename);
                        //手动设置maxLength为MaxLength
                        InputFilter[] filters = {new InputFilter.LengthFilter(MaxLength)};
                        et_content.setFilters(filters);
                    }
                }else {
                    if (titlename.equals("心里话")){
                        type = 44;
                        publish_menu_type.setVisibility(View.GONE);
                        publish_menu_type_line.setVisibility(View.GONE);
                    }else if (titlename.equals("生活分享")){
                        type = 30;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                    }else if (titlename.equals("笔记") || titlename.equals("优秀笔记")){
                        type = 116;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                    }else if (titlename.equals("话题探索")){
                        type = 21;
                        publish_menu_type.setVisibility(View.GONE);
                        publish_menu_type_line.setVisibility(View.GONE);

                    }else {
                        publish_menu_type_text.setText(titlename);
                        //手动设置maxLength为MaxLength
                        InputFilter[] filters = {new InputFilter.LengthFilter(MaxLength)};
                        et_content.setFilters(filters);
                    }
                }


            }
        }else {

            if (getIntent().getIntExtra("status",0) == 5){
                status = 5;
                publish_menu_visible_text.setText("新增内容");
            }

            if (!CommonUtils.isEmpty(titlename)){
                topbar.getTitleView().setText(titlename);
                et_content.setHint(CommonUtils.formatString(getIntent().getStringExtra("tipname")));
                String n = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.NoNameKey,"0");
                if (n.equals("1")){
                    if (titlename.equals("心里话")){
                        type = 44;
                        publish_menu_type_title.setText("昵称显示");
                        publish_menu_type_text.setText("公开昵称");
                    }else if (titlename.equals("生活分享")){
                        type = 30;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                        et_content.setText(CommonUtils.formatString(getIntent().getStringExtra("signtext")));
                    }else if (titlename.equals("笔记") || titlename.equals("优秀笔记")){
                        type = 116;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                        et_content.setText(CommonUtils.formatString(getIntent().getStringExtra("signtext")));
                    }else if (titlename.equals("话题探索")){
                        type = 21;
                        publish_menu_type_title.setText("昵称显示");
                        publish_menu_type_text.setText("公开昵称");
//                    publish_menu_type.setVisibility(View.GONE);
//                    publish_menu_type_line.setVisibility(View.GONE);
                    }else {//微句
                        //手动设置maxLength为MaxLength
                        InputFilter[] filters = {new InputFilter.LengthFilter(MaxLength)};
                        et_content.setFilters(filters);
                        if (!CommonUtils.isEmpty(titlename) && type > 0){
                            publish_menu_type_text.setText(titlename);
                        }
                    }
                }else {
                    if (titlename.equals("心里话")){
                        type = 44;
                        publish_menu_type.setVisibility(View.GONE);
                        publish_menu_type_line.setVisibility(View.GONE);
                    }else if (titlename.equals("生活分享")){
                        type = 30;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                        et_content.setText(CommonUtils.formatString(getIntent().getStringExtra("signtext")));
                    }else if (titlename.equals("笔记") || titlename.equals("优秀笔记")){
                        type = 116;
                        publish_menu_type_title.setText("所在位置");
                        publish_menu_type_text.setText("");
                        et_content.setText(CommonUtils.formatString(getIntent().getStringExtra("signtext")));
                    }else if (titlename.equals("话题探索")){
                        type = 21;
                        publish_menu_type.setVisibility(View.GONE);
                        publish_menu_type_line.setVisibility(View.GONE);
                    }else {//微句
                        //手动设置maxLength为MaxLength
                        InputFilter[] filters = {new InputFilter.LengthFilter(MaxLength)};
                        et_content.setFilters(filters);
                        if (!CommonUtils.isEmpty(titlename) && type > 0){
                            publish_menu_type_text.setText(titlename);
                        }
                    }
                }

                String content = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.WeiJuDraftKey, "");
                if (!CommonUtils.isEmpty(content)){//读取草稿文字
                    et_content.setText(content);
                }

            }else {
                //手动设置maxLength为MaxLength
                InputFilter[] filters = {new InputFilter.LengthFilter(MaxLength)};
                et_content.setFilters(filters);
                et_content.setText(CommonUtils.formatString(getIntent().getStringExtra("signtext")));
                if (!CommonUtils.isEmpty(titlename) && type > 0){
                    publish_menu_type_text.setText(titlename);
                }

                if (et_content.getText() == null || et_content.getText().length() == 0){
                    String content = SPManageUtils.getInstance(CustomApplication.mContext).getSPString(AdvertUtils.WeiJuDraftKey, "");
                    if (!CommonUtils.isEmpty(content)){//读取草稿文字
                        et_content.setText(content);
                    }
                }

            }
        }
        originImages = getIntent().getStringArrayListExtra("img");
        if (originImages == null){
            originImages = new ArrayList<String>();
        }
        mContext = getApplicationContext();
        if (PermissionUtils.hasSDCard() == true){
            InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
        }
        //添加按钮图片资源
        String plusPath = getString(R.string.glide_plus_icon_string) + AppUtils.getPackageInfo(mContext).packageName + "/mipmap/" + R.mipmap.bg_add_imgshow;
        dragImages = new ArrayList<>();
        originImages.add(plusPath);//添加按键，超过9张时在adapter中隐藏
        dragImages.addAll(originImages);
        new Thread(new MyRunnable(dragImages, originImages, dragImages, myHandler, false)).start();//开启线程，在新线程中去压缩图片

        if (type == 30 || type == 44 || type == 116){// || type == 21
            publish_menu_original_line.setVisibility(View.GONE);
            publish_menu_original.setVisibility(View.GONE);
        }else {
            publish_menu_original_line.setVisibility(View.VISIBLE);
            publish_menu_original.setVisibility(View.VISIBLE);
            publish_menu_original.setClickable(true);
            publish_menu_original.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (original.equals("1")){
                        original = "0";
                        publish_menu_original_select.setImageResource(R.drawable.ios7_switch_off);
                    }else {
                        original = "1";
                        publish_menu_original_select.setImageResource(R.drawable.ios7_switch_on);
                    }
                }
            });
        }

        TextView publish_tip = (TextView) findViewById(R.id.publish_tip);
        if (type == 30 || type == 44 || type == 116){
            publish_tip.setText("长按图片可以拖动更换位置或者删除~");
            maxImgCount = 9;
        }else if (type == 21){
            publish_tip.setText("设置话题封面(长按拖动删除)");
            maxImgCount = 9;//maxImgCount = 1;
        }else {
            publish_tip.setText("设置微句封面(长按拖动删除)");
            maxImgCount = 9;//maxImgCount = 1;
        }

    }

    private void initView() {
        rcvImg = (RecyclerView) findViewById(R.id.rcv_img);
        tv = (TextView) findViewById(R.id.tv);
        et_content = (EditText) findViewById(R.id.et_content);
    }

    private void pictureMenu(){
        if (isPublishing == true){
            ToastUtil.show(LangPublishActivity.this, "正在发布...");
            return;
        }
        if (isDealWithImg == true){
            ToastUtil.show(LangPublishActivity.this, "正在处理图片，请稍后...");
            return;
        }

        List<String> itemList = new ArrayList<String>();
        itemList.add("拍一张");
        itemList.add("从相册选择");
        ActionSheetDialog actionSheetDialog = new ActionSheetDialog(LangPublishActivity.this)
                .builder()
                .setTitle("请选择")
                .setCancelable(false)
                .setCanceledOnTouchOutside(true);
        for (String s : itemList){
            actionSheetDialog.addSheetItem(s, null, new ActionSheetDialog.OnSheetItemClickListener() {
                @Override
                public void onClick(int which) {
                    if (which > 0){
                        int fiterType = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.FilterCoverKey, 0);
                        if (which == 1){
                            if (type == 30 || type == 44 || type == 116 || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//5.0以下手机不裁剪
                                doTakePhoto();
                            }else {
                                if (fiterType == 0){//关闭滤镜
                                    doTakePhoto();
                                }else {
                                    takeOnePhoto();
                                }
                            }
                        }else if (which == 2){
                            if (type == 30 || type == 44 || type == 116 || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){//5.0以下手机不裁剪
                                PermissionUtils.isPictureNote(LangPublishActivity.this, new PermissionCallback() {
                                    @Override
                                    public void onResult(boolean flag, boolean showAlert) {
                                        if(flag == true){
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                                                final int maxNumPhotosAndVideos = maxImgCount - originImages.size() + 1;
                                                Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                                                intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
                                                startActivityForResult(intent, PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE);
                                                return;
                                            }
                                            MultiImageSelector.create()
                                                    .showCamera(false)
                                                    .count(maxImgCount - originImages.size() + 1)
                                                    .multi()
                                                    .start(LangPublishActivity.this, REQUEST_PUBLISH);
                                        }
                                    }
                                });
                            }else {
                                if (fiterType == 0){//关闭滤镜
                                    PermissionUtils.isPictureNote(LangPublishActivity.this, new PermissionCallback() {
                                        @Override
                                        public void onResult(boolean flag, boolean showAlert) {
                                            if(flag == true){
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                                                    if (ContextCompat.checkSelfPermission(LangPublishActivity.this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED){
                                                        ActivityCompat.requestPermissions(LangPublishActivity.this, new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES},
                                                                MainActivity.REQUEST_PERMISSION);
                                                        return;
                                                    }
                                                }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                                                        && ContextCompat.checkSelfPermission(LangPublishActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                                    ActivityCompat.requestPermissions(LangPublishActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                                            REQUEST_PERMISSION);
                                                    //ToastUtil.show(ShareActivity.this,"亲，请开启应用对SD卡的读写权限");
                                                    return;
                                                }
                                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
                                                    final int maxNumPhotosAndVideos = maxImgCount - originImages.size() + 1;
                                                    Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                                                    intent.putExtra(MediaStore.EXTRA_PICK_IMAGES_MAX, maxNumPhotosAndVideos);
                                                    startActivityForResult(intent, PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE);
                                                    return;
                                                }
                                                MultiImageSelector.create()
                                                        .showCamera(false)
                                                        .count(maxImgCount - originImages.size() + 1)
                                                        .multi()
                                                        .start(LangPublishActivity.this, REQUEST_PUBLISH);
                                            }
                                        }
                                    });
                                }else {
                                    doPickPhotoFromGallery();
                                }
                            }

                        }
                    }
                }
            });
        }
        actionSheetDialog.show();
    }

    private void initRcv() {

        postArticleImgAdapter = new PostArticleImgAdapter(mContext, dragImages, maxImgCount);
        rcvImg.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));
        rcvImg.setAdapter(postArticleImgAdapter);

        MyCallBack myCallBack = new MyCallBack(postArticleImgAdapter, dragImages, originImages);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rcvImg);//绑定RecyclerView

        //事件监听
        rcvImg.addOnItemTouchListener(new OnRecyclerItemClickListener(rcvImg) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                if (originImages.get(vh.getAdapterPosition()).contains(getString(R.string.glide_plus_icon_string))) {//打开相册
                    pictureMenu();
                } else {
                    onClickImageView(vh.itemView, vh.getAdapterPosition());
                    //ToastUtils.getInstance().show(CustomApplication.customApplication, "预览图片");
                }
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //如果item不是最后一个，则执行拖拽
                if (vh.getLayoutPosition() != dragImages.size() - 1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });

        myCallBack.setDragListener(new MyCallBack.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    tv.setBackgroundResource(R.color.holo_red_dark);
                    tv.setText(getResources().getString(R.string.post_delete_tv_s));
                } else {
                    tv.setText(getResources().getString(R.string.post_delete_tv_d));
                    tv.setBackgroundResource(R.color.holo_red_light);
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    tv.setVisibility(View.VISIBLE);
                } else {
                    tv.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {

            }
        });
    }

    /**拍照获取相片**/
    private void doTakePhoto() {
        PermissionUtils.showCamaraNote(LangPublishActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        imageFileName = System.currentTimeMillis() + Constant.weijuTakePhoto;
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(LangPublishActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });
    }

    /**拍照获取相片**/
    private void takeOnePhoto() {
        PermissionUtils.showCamaraNote(LangPublishActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if(flag == true){
                    if (PermissionUtils.cameraIsCanUse() == true){
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机
                        imageFileName = System.currentTimeMillis() + Constant.weijuTakePhoto;
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));
                        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                        //直接使用，没有缩小
                        startActivityForResult(intent, TAKE_PICTURE);  //用户点击了从相机获取
                    }else {
                        ActivityCompat.requestPermissions(LangPublishActivity.this,
                                new String[]{Manifest.permission.CAMERA},
                                1);
                    }
                }
            }
        });

    }


    public static Uri getUriFromFile(Context context, File file) {
        Uri imageUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(context,
                    "com.zhongshengnetwork.rightbe.fileprovider", file);//通过FileProvider创建一个content类型的Uri
        } else {
            imageUri = Uri.fromFile(file);
        }
        return imageUri;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            pictureMenu();
        } else {
            // 权限被用户拒绝了，可以提示用户,关闭界面等等。
            CustomDialog dialog = null;
            final CustomDialog.Builder builder = new CustomDialog.Builder(LangPublishActivity.this);
            builder.setTitle("温馨提示");
            builder.setMessage("应用需要开启相机权限，是否去设置？");
            builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    //跳转App设置权限的界面
                    Intent i = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
                    String pkg = "com.android.settings";
                    String cls = "com.android.settings.applications.InstalledAppDetails";
                    i.setComponent(new ComponentName(pkg, cls));
                    i.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(i);
                    finish();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog = builder.create();
            dialog.show();

        }
    }

    //------------------图片相关-----------------------------

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //ToastUtil.show(LangPublishActivity.this,"requestCode="+requestCode+"，resultCode="+resultCode);
        int fiterType = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.FilterCoverKey, 0);
        if (requestCode == REQUEST_PUBLISH && resultCode == RESULT_OK) {//从相册选择完图片
            if (data == null){
                return;
            }
            if (type == 30 || type == 44 || type == 116 || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || fiterType == 0){
                postArticleImgAdapter.filterIndex = 0;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.show();
                    }
                });
                isDealWithImg = true;
                //压缩图片
                new Thread(new MyRunnable(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT),
                        originImages, dragImages, myHandler, true)).start();
            }else {
                try{
                    Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0)));
                    if (imageUri == null){
                        return;
                    }
                    cropImage(imageUri);
                }catch (Exception e){
                    ToastUtil.show(LangPublishActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                    LangPublishActivity.uploadError("微句选择封面报错："+e.getLocalizedMessage());
                }

            }
        }else if (requestCode == LANG_TYPE && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            //选择了微句类型
            type = data.getIntExtra("type",0);
            String typeName = data.getStringExtra("typename");
            if (!CommonUtils.isEmpty(typeName)){
                publish_menu_type_text.setText(typeName);
            }
            Log.e("TAG","选择了微句类型："+type+"\n");
        }else if (requestCode == REQUEST_LOCATION && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            nation = "";
            province = data.getStringExtra(APIKey.provinceKey);
            city = data.getStringExtra(APIKey.cityKey);
            area = "";
            location = data.getStringExtra(APIKey.locationKey);
            longtitude = data.getDoubleExtra(APIKey.longtitudeKey,0.0f);
            latitude = data.getDoubleExtra(APIKey.latitudeKey,0.0f);
            publish_menu_type_text.setText(location);
        }else if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){

            try {
                Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));
                if (imageUri == null){
                    ToastUtil.show(LangPublishActivity.this,"没有图片");
                    return;
                }
                cropSelectImage(imageUri);
            }catch (Exception e){
                ToastUtil.show(LangPublishActivity.this,"亲，你这次没拍好哦，再来一次哟~");
                LangPublishActivity.uploadError("微句拍照封面报错："+e.getLocalizedMessage());
            }

            /*
            if (type == 30 || type == 44 || type == 116 || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP || fiterType == 0){
                postArticleImgAdapter.filterIndex = 0;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.show();
                    }
                });
                isDealWithImg = true;
                ArrayList<String> imgList = new ArrayList<String>();
                //Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),imageFileName));
                imgList.add(imageFileName);
                //imgList.add(imageUri.getPath());
                new Thread(new MyRunnable(imgList,
                        originImages, dragImages, myHandler, true)).start();
            }else {
                try {
                    Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),"image.jpg"));
                    if (imageUri == null){
                        ToastUtil.show(LangPublishActivity.this,"没有图片");
                        return;
                    }
                    cropSelectImage(imageUri);
                }catch (Exception e){
                    ToastUtil.show(LangPublishActivity.this,"亲，你这次没拍好哦，再来一次哟~");
                    LangPublishActivity.uploadError("微句拍照封面报错："+e.getLocalizedMessage());
                }

            }
            */

        }else if (requestCode == SELECT_WZT && resultCode == RESULT_OK){
            if (data != null){
                wztId = data.getStringExtra("weijuId");
                wztTitle = data.getStringExtra("title");
                publish_menu_wzt_text.setText(wztTitle);
            }
        }else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK){
            if (data == null){
                return;
            }
            try {
                final Uri resultUri = UCrop.getOutput(data);
                Bitmap bmap = BitmapFactory.decodeFile(resultUri.getEncodedPath());
                if (bmap != null){

                    postArticleImgAdapter.filterIndex = 0;

                    //2020年11月29日去掉滤镜
                    /*
                    cropFilePath = resultUri.getPath();
                    Intent intent = new Intent(LangPublishActivity.this, FilterActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putParcelable("Uri",resultUri);
                    intent.putExtras(bundle);//发送数据
                    startActivityForResult(intent, FILTER_PICTURE);
                    */


                    ArrayList<String> imgList = new ArrayList<String>();
                    imgList.add(resultUri.getPath());
                    new Thread(new MyRunnable(imgList,
                            originImages, dragImages, myHandler, true)).start();

                }
            }catch (Exception e){
                ToastUtil.show(LangPublishActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                LangPublishActivity.uploadError("微句裁剪封面报错："+e.getLocalizedMessage());
            }

        }else if(requestCode == FILTER_PICTURE && resultCode == RESULT_OK){
            if (!CommonUtils.isEmpty(cropFilePath)){

                if (data != null){
                    int filterIndex = data.getIntExtra("filterIndex", 0);
                    postArticleImgAdapter.filterIndex = filterIndex;
                }else {
                    postArticleImgAdapter.filterIndex = 0;
                }

                ArrayList<String> imgList = new ArrayList<String>();
                imgList.add(cropFilePath);
                new Thread(new MyRunnable(imgList,
                        originImages, dragImages, myHandler, true)).start();
            }

        } else if (requestCode == CHOOSE_PICTURE && resultCode == RESULT_OK){//从相册选择一张进行裁剪
            if (data != null){

                ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
                if (resultPhotos != null && resultPhotos.size() > 0){
                    Photo photo = resultPhotos.get(0);
                    try{
                        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(photo.path));
                        if (imageUri == null){
                            return;
                        }
                        cropSelectImage(imageUri);
                    }catch (Exception e){
                        ToastUtil.show(LangPublishActivity.this, "亲，你选择的图片不可用，请选取其他图片试试哦");
                        LangPublishActivity.uploadError("微句选择封面报错："+e.getLocalizedMessage());
                    }


                }

            }
        }else if(requestCode == PHOTO_PICKER_REQUEST_CODE && resultCode == RESULT_OK){//android 13
            if (data != null){
                cropSelectImage(data.getData());
            }
        }else if(requestCode == PHOTO_PICKER_MULTI_SELECT_REQUEST_CODE && resultCode == RESULT_OK){//android 13
            if (data != null){
                ArrayList<String> imgList = new ArrayList<String>();
                for (int i = 0; i < data.getClipData().getItemCount(); i++) {
                    Uri currentUri = data.getClipData().getItemAt(i).getUri();
                    imgList.add(getRealFilePath(CustomApplication.mContext, currentUri));
                    // Do stuff with each photo/video URI.
                }

                postArticleImgAdapter.filterIndex = 0;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.show();
                    }
                });
                isDealWithImg = true;
                //压缩图片
                new Thread(new MyRunnable(imgList,
                        originImages, dragImages, myHandler, true)).start();
            }
        }
    }

    public String getRealFilePath( final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 另起线程压缩图片
     */
    static class MyRunnable implements Runnable {

        ArrayList<String> images;
        ArrayList<String> originImages;
        ArrayList<String> dragImages;
        Handler handler;
        boolean add;//是否为添加图片

        public MyRunnable(ArrayList<String> images, ArrayList<String> originImages, ArrayList<String> dragImages, Handler handler, boolean add) {
            this.images = images;
            this.originImages = originImages;
            this.dragImages = dragImages;
            this.handler = handler;
            this.add = add;
        }

        @Override
        public void run() {

            SdcardUtils sdcardUtils = new SdcardUtils();
            String filePath;
            Bitmap newBitmap;
            int addIndex = originImages.size() - 1;
            for (int i = 0; i < images.size(); i++) {
                if (images.get(i).contains(CustomApplication.customApplication.getString(R.string.glide_plus_icon_string))) {//说明是添加图片按钮
                    continue;
                }

                if(images.get(i).contains("http")){
                    filePath = images.get(i);
                }else {
                    filePath = images.get(i);
                }
                //设置值
                if (!add) {
                    images.set(i, filePath);
                } else {//添加图片，要更新
                    dragImages.add(addIndex, filePath);
                    originImages.add(addIndex++, filePath);
                }
            }
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);

        }
    }

    private MyHandler myHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            LangPublishActivity activity = (LangPublishActivity) reference.get();
            if (activity != null) {
                if (msg == null){
                    return;
                }
                switch (msg.what) {
                    case 1:
                        activity.isDealWithImg = false;
                        activity.avi.hide();
                        activity.postArticleImgAdapter.notifyDataSetChanged();
                        break;
                }
            }
        }
    }

    //以下是发布流程
    private void publishLang(){

        if (bindMobile() == true){
            return;
        }

        if (LangPublishActivity.this == null){
            //活动已经销毁了
            return;
        }

        if(isDealWithImg == true){
            ToastUtil.show(LangPublishActivity.this, "正在处理图片，请稍后...");
            return;
        }

        if (isPublishing == true){
            ToastUtil.show(LangPublishActivity.this, "发布中，请稍后...");
            return;
        }

        if (et_content.getText().length() == 0){
            ToastUtil.show(LangPublishActivity.this, "请输入发布的内容~");
            return;
        }

        if(type == 0){
            String typeselect = SPManageUtils.getInstance(CustomApplication.mContext).getSPString("typeselect","0");
            if(!typeselect.equals("0")){
                ToastUtil.show(LangPublishActivity.this, "请设置类型哦~");
                return;
            }
        }

        String title = et_content.getText().toString();

        if (type == 21){
            if (dragImages != null && dragImages.size() > 1){

            }else {
                ToastUtil.show(LangPublishActivity.this, "请设置话题封面哦~");
                return;
            }
        }

        isPublishing = true;
        if (isRepublish == true){
            /*
            avi.setVisibility(View.VISIBLE);
            avi.show();
            imgString = "";
            if (dragImages != null && dragImages.size() > 0){
                getUploadInfo();
            }else {
                uploadLang();
            }
            */
            final JsonMap<String, String> map = new JsonMap<String, String>();
            map.put(APIKey.titleKey, title.replaceAll("%","﹪"));
            map.put("type",type+"");
            map.put("status",status+"");
            if (!CommonUtils.isEmpty(createtime)){
                map.put("time", createtime);
            }
            map.put(APIKey.nationKey,nation);
            map.put(APIKey.provinceKey,province);
            map.put(APIKey.cityKey,city);
            map.put(APIKey.areaKey,area);
            map.put(APIKey.locationKey,location);
            map.put(APIKey.longtitudeKey,longtitude+"");
            map.put(APIKey.latitudeKey,latitude+"");
            map.put("noname",noname);
            map.put("original",original);
            map.put("version", BuildConfig.VERSION_CODE+"");
            if (!CommonUtils.isEmpty(wztId)){
                map.put("weijuId", wztId);
            }
            map.put(APIKey.idKey,mLangid);
            LangPublishdbModel model = new LangPublishdbModel();
            model.setData(map.toString());
            if (dragImages != null && dragImages.size() > 0){
                model.setImgdata(CommonUtils.listToString(dragImages));
            }else {
                model.setImgdata("");
            }
            model.setUserid(CustomApplication.loginModel.getUid());
            model.setDatatype(1);
            model.setFilter(postArticleImgAdapter.filterIndex);
            LangPublishService.saveOrUpdate(model);
            Intent intent = new Intent();
            intent.putExtra("isBacken", true);
            setResult(RESULT_OK, intent);
            finish();
            return;
        }

        //新发布的，先检测是否发布过类似的
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.titleKey, title.replaceAll("%","﹪"));
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        if (!CommonUtils.isEmpty(createtime)){
            map.put("timing", "1");
        }
        String url = "miniapp/langappid/publishcheck.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    if (commonModel.getData() != null && commonModel.getData().toString().equals("0")){//老的发布
                        avi.setVisibility(View.VISIBLE);
                        avi.show();
                        imgString = "";
                        if (dragImages != null && dragImages.size() > 0){
                            getUploadInfo();
                        }else {
                            uploadLang();
                        }
                    }else {//全新发布方式
                        final JsonMap<String, String> map = new JsonMap<String, String>();
                        String title = et_content.getText().toString().replaceAll("%","﹪");
                        map.put(APIKey.titleKey, title);
                        map.put("type",type+"");
                        map.put("status",status+"");
                        if (!CommonUtils.isEmpty(createtime)){
                            map.put("time", createtime);
                        }
                        map.put(APIKey.nationKey,nation);
                        map.put(APIKey.provinceKey,province);
                        map.put(APIKey.cityKey,city);
                        map.put(APIKey.areaKey,area);
                        map.put(APIKey.locationKey,location);
                        map.put(APIKey.longtitudeKey,longtitude+"");
                        map.put(APIKey.latitudeKey,latitude+"");
                        map.put("noname",noname);
                        map.put("original",original);
                        map.put("version", BuildConfig.VERSION_CODE+"");
                        if (!CommonUtils.isEmpty(wztId)){
                            map.put("weijuId", wztId);
                        }
                        LangPublishdbModel model = new LangPublishdbModel();
                        model.setData(map.toString());
                        if (dragImages != null && dragImages.size() > 0){
                            model.setImgdata(CommonUtils.listToString(dragImages));
                        }else {
                            model.setImgdata("");
                        }
                        model.setUserid(CustomApplication.loginModel.getUid());
                        model.setDatatype(1);
                        model.setFilter(postArticleImgAdapter.filterIndex);
                        LangPublishService.saveOrUpdate(model);

                        if (status == 5){
                            Intent mIntent = new Intent(BroadcastDefine.WJ_AUTO_PUBLISH_Action);
                            //发送广播
                            sendBroadcast(mIntent);
                            et_content.setText("");
                            isPublishing = false;
                            if (originImages == null){
                                originImages = new ArrayList<String>();
                            }else {
                                originImages.clear();
                            }
                            if (dragImages == null){
                                dragImages = new ArrayList<String>();
                            }else {
                                dragImages.clear();
                            }
                            mContext = getApplicationContext();
                            if (PermissionUtils.hasSDCard() == true){
                                InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
                            }
                            //添加按钮图片资源
                            String plusPath = getString(R.string.glide_plus_icon_string) + AppUtils.getPackageInfo(mContext).packageName + "/mipmap/" + R.mipmap.bg_add_imgshow;
                            originImages.add(plusPath);//添加按键，超过9张时在adapter中隐藏
                            dragImages.addAll(originImages);
                            new Thread(new MyRunnable(dragImages, originImages, dragImages, myHandler, false)).start();//开启线程，在新线程中去压缩图片

                            ToastUtil.show(LangPublishActivity.this, "内容已提交，你可以继续发布");
                        }else {
                            Intent intent = new Intent();
                            intent.putExtra("isBacken", true);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    }
                }else {
                    CustomApplication.showTip(commonModel, LangPublishActivity.this);
                    isPublishing = false;
                    /*
                    if(type == 30 || type == 44 || type == 116){
                        final JsonMap<String, String> map = new JsonMap<String, String>();
                        map.put(APIKey.titleKey, et_content.getText().toString().replaceAll("%","﹪"));
                        map.put("type",type+"");
                        map.put("status",status+"");
                        if (!CommonUtils.isEmpty(createtime)){
                            map.put("time", createtime);
                        }
                        map.put(APIKey.nationKey,nation);
                        map.put(APIKey.provinceKey,province);
                        map.put(APIKey.cityKey,city);
                        map.put(APIKey.areaKey,area);
                        map.put(APIKey.locationKey,location);
                        map.put(APIKey.longtitudeKey,longtitude+"");
                        map.put(APIKey.latitudeKey,latitude+"");
                        map.put("noname",noname);
                        map.put("original",original);
                        map.put("version", BuildConfig.VERSION_CODE+"");
                        if (!CommonUtils.isEmpty(wztId)){
                            map.put("weijuId", wztId);
                        }
                        LangPublishdbModel model = new LangPublishdbModel();
                        model.setData(map.toString());
                        if (dragImages != null && dragImages.size() > 0){
                            model.setImgdata(CommonUtils.listToString(dragImages));
                        }else {
                            model.setImgdata("");
                        }
                        model.setUserid(CustomApplication.loginModel.getUid());
                        model.setDatatype(1);
                        model.setFilter(postArticleImgAdapter.filterIndex);
                        LangPublishService.saveOrUpdate(model);
                        Intent intent = new Intent();
                        intent.putExtra("isBacken", true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }else {
                        CustomApplication.showTip(commonModel, LangPublishActivity.this);
                        isPublishing = false;
                    }
                    */
                }
            }

            @Override
            public void onError(String msg) {
                isPublishing = false;
            }
        });
    }

    //上传内容
    private void uploadLang(){

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.titleKey, et_content.getText().toString().replaceAll("%","﹪"));
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("img",imgString);
        map.put("type",type+"");
        map.put("status",status+"");
        map.put("time", CommonUtils.formatString(createtime));
        map.put(APIKey.nationKey,nation);
        map.put(APIKey.provinceKey,province);
        map.put(APIKey.cityKey,city);
        map.put(APIKey.areaKey,area);
        map.put(APIKey.locationKey,location);
        map.put(APIKey.longtitudeKey,longtitude+"");
        map.put(APIKey.latitudeKey,latitude+"");
        map.put("noname",noname);
        map.put("original",original);
        map.put("version", BuildConfig.VERSION_CODE+"");
        if (!CommonUtils.isEmpty(wztId)){
            map.put("weijuId", wztId);
        }
        String url = "miniapp/langappid/publishlang.do";
        if (isRepublish == true){
            url = "miniapp/langappid/editlang.do";
            map.put(APIKey.idKey,mLangid);
        }
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            deleteTempFile();
                            avi.hide();
                            //isPublishing = false;
                            ToastUtil.show(LangPublishActivity.this, "发布成功");
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            avi.hide();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel, LangPublishActivity.this);
                        }
                    }
                });

            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.hide();
                        isPublishing = false;
                        ToastUtil.show(LangPublishActivity.this,"发布失败，请稍后重试");
                    }
                });

            }
        });
    }

    //删除临时文件
    private void deleteTempFile(){
        /*
        if (dragImages != null && dragImages.size() > 0){//删除发布过程中生成的图片
            imgIndex = 0;
            for (;imgIndex < dragImages.size(); imgIndex++){
                if (dragImages.get(imgIndex).contains("http")==false){
                    Bitmap bitmap = ImageUtils.getBitmap(dragImages.get(imgIndex));
                    if (bitmap != null){
                        if (CommonUtils.deleteFileByPath(dragImages.get(imgIndex))==true){
                            Log.e("TAG","发布完成文件删除成功:"+dragImages.get(imgIndex));
                        }
                    }
                }
            }
        }
        */
    }

    //获取上传图片凭证
    private void getUploadInfo(){
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        HttpsUtils.getQiniuTokenDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                final CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){
                    qiniuModel = GsonTools.getQiniuModel(data);
                    if (qiniuModel != null){
                        imgIndex = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //接着开定时器上传图片
                                startTimer();
                            }
                        });

                    }
                }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            avi.hide();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel,LangPublishActivity.this);
                        }
                    });

                }
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        avi.hide();
                        isPublishing = false;
                        ToastUtil.show(LangPublishActivity.this,"发布失败");
                    }
                });
            }
        });
    }

    //上传图片
    private void uploadImg(Bitmap bitmap, final int index){
        final String name = System.currentTimeMillis()+CustomApplication.loginModel.getUid()+".jpg";
        CommonUtils.uploadBytesToQiniu(qiniuModel.getUploadtoken(), qiniuModel.getUploadurl(), name, CommonUtils.bitmapToBytes(bitmap), new QiniuCallBack() {
            @Override
            public void onSuccess(String data) {
                if (CommonUtils.isEmpty(data)){
                    uploadError("发布失败，把图片删除再试试~");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            stopTimer();
                            avi.hide();
                            isPublishing = false;
                            isUploading = false;
                            ToastUtil.show(LangPublishActivity.this,"发布失败，请稍后重新发布~");
                        }
                    });

                }else {
                    if (imgString.length() >0){
                        imgString += ",";
                    }
                    imgString += data;
                    isUploading = false;
                }
            }

            @Override
            public void onModelSuccess(QiniuUploadModel data) {

            }

            @Override
            public void onError(String msg) {
                uploadError("上传图片错误信息："+CommonUtils.formatString(msg));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        stopTimer();
                        avi.hide();
                        isPublishing = false;
                        isUploading = false;
                        ToastUtil.show(LangPublishActivity.this,"发布失败，请稍后再试试~");
                    }
                });
            }
        });
    }

    private void startTimer(){

        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    sendMessage(1);
                }
            };
        }
        if(mTimer != null && mTimerTask != null ){
            mTimer.schedule(mTimerTask, delay, period);
            timerFlag = true;
        }

    }

    private void stopTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
            timerFlag = false;
        }
    }

    public void sendMessage(int id){
        if (mHandler != null) {
            Message message = Message.obtain(mHandler, id);
            mHandler.sendMessage(message);
        }
    }

    //点击图片处理
    private void onClickImageView(View view, int position){
        Log.e("TAG","当前位置："+position);

        if (dragImages == null || dragImages.size() < 2){
            return;
        }

        if (CustomApplication.isWatchingImg == true){
            return;
        }
        CustomApplication.isWatchingImg = true;

        Intent intent = new Intent(LangPublishActivity.this, SelfImagePreviewActivity.class);
        intent.putExtra("number",4);
        intent.putExtra("position",position);
        intent.putExtra("isListImg",true);
        intent.putExtra("filterIndex", postArticleImgAdapter.filterIndex);
        String imgs = "";
        for (int i = 0; i < dragImages.size()-1; i++){
            if(i > 0){
                imgs+=",";
            }
            /*
            if (CommonUtils.fileIsExists(dragImages.get(i))){
                Log.e("TAG","存在图片："+imgs);
            }else {
                Log.e("TAG","不存在图片："+imgs);
            }
            */
            imgs+=dragImages.get(i);
            intent.putExtra("imgs",imgs);
        }


        //View代表方法传入的控件
        int[] viewLocation = new int[2];
        view.getLocationInWindow(viewLocation);
        int viewX = viewLocation[0]; // x 坐标
        int viewY = viewLocation[1];//-(int) (20*ScreenUtils.getScreenDensity(CustomApplication.mContext)); // y 坐标，这里当顶部有状态栏时，要减去状态栏的高度
        intent.putExtra("viewX",viewX);
        intent.putExtra("viewY",viewY);
        intent.putExtra("imgW",imgW);
        intent.putExtra("imgH",imgW);
        startActivity(intent);
        overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.

    }

    //上传错误
    public static void uploadError(String msg){
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("msg", msg);
        if (CustomApplication.loginModel != null) {
            map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        }
        String url = "miniapp/langappid/geterror.do";
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                Log.e("上传错误",data+"\n");
            }

            @Override
            public void onError(String msg) {
                Log.e("上传错误信息",msg+"\n");
            }
        });

    }

    /**从相册获取图片**/
    private void doPickPhotoFromGallery() {
        PermissionUtils.isPictureNote(LangPublishActivity.this, new PermissionCallback() {
            @Override
            public void onResult(boolean flag, boolean showAlert) {
                if (flag == true){
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
                        startActivityForResult(intent, PHOTO_PICKER_REQUEST_CODE);
                        return;
                    }else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                            && ContextCompat.checkSelfPermission(LangPublishActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(LangPublishActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                REQUEST_PERMISSION);
                        //ToastUtil.show(LangPublishActivity.this,"亲，请开启应用对SD卡的读写权限");
                        return;
                    }

                    EasyPhotos.createAlbum(LangPublishActivity.this, false, GlideEngine.getInstance())
                            .start(CHOOSE_PICTURE);
                }
            }
        });

    }

    //裁剪
    private void cropImage(Uri uri){

        int x = 30;
        int y = 17;
        int fiterType = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.FilterCoverKey, 0);
        switch (fiterType){
            case Crop_Type_30_17:
                x = 30;
                y = 17;
                break;
            case Crop_Type_1_1:
                x = 1;
                y = 1;
                break;
            case Crop_Type_16_9:
                x = 16;
                y = 9;
                break;
            case Crop_Type_3_2:
                x = 3;
                y = 2;
                break;
            case Crop_Type_4_3:
                x = 4;
                y = 3;
                break;
            case Crop_Type_2_1:
                x = 2;
                y = 1;
                break;
            case Crop_Type_2_3:
                x = 2;
                y = 3;
                break;
            case Crop_Type_3_4:
                x = 3;
                y = 4;
                break;
        }

        Uri imageUri = getUriFromFile(CustomApplication.mContext,new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto));
        float density = ScreenUtils.getScreenDensity(LangPublishActivity.this);
        UCrop.of(uri, imageUri)//"imageout.jpg"
                .withAspectRatio(x, y)
                .withMaxResultSize((int)(1920*density), (int)(1920*density))
                .start(LangPublishActivity.this);

    }

    //裁剪
    private void cropSelectImage(Uri uri){

        int x = 30;
        int y = 17;
        int fiterType = SPManageUtils.getInstance(CustomApplication.mContext).getSPInt(AdvertUtils.FilterCoverKey, 0);
        switch (fiterType){
            case Crop_Type_30_17:
                x = 30;
                y = 17;
                break;
            case Crop_Type_1_1:
                x = 1;
                y = 1;
                break;
            case Crop_Type_16_9:
                x = 16;
                y = 9;
                break;
            case Crop_Type_3_2:
                x = 3;
                y = 2;
                break;
            case Crop_Type_4_3:
                x = 4;
                y = 3;
                break;
            case Crop_Type_2_1:
                x = 2;
                y = 1;
                break;
            case Crop_Type_2_3:
                x = 2;
                y = 3;
                break;
            case Crop_Type_3_4:
                x = 3;
                y = 4;
                break;
        }
        float density = ScreenUtils.getScreenDensity(LangPublishActivity.this);
        if (fiterType == 0 || postArticleImgAdapter.filterIndex == 0){//不裁剪
            UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto)))//"imageout.jpg"
                    .useSourceImageAspectRatio()
                    .withMaxResultSize((int)(1920*density), (int)(1920*density))
                    .start(LangPublishActivity.this);
            return;
        }

        UCrop.of(uri, Uri.fromFile(new File(CommonUtils.getFile(Environment.DIRECTORY_PICTURES),System.currentTimeMillis() + Constant.weijuTakePhoto)))//"imageout.jpg"
                .withAspectRatio(x, y)
                .withMaxResultSize((int)(1920*density), (int)(1920*density))
                .start(LangPublishActivity.this);
    }

}
